package cn.maxhou.t0001;

import java.lang.reflect.Proxy;

public class LogTest {
    public static void main(String[] args) {
       //创建原始对象
        LogService logService=new LogServiceImpl();

        //创建代理对象
        LogService proxyInstance=(LogService) Proxy.newProxyInstance(
                logService.getClass().getClassLoader(),
                logService.getClass().getInterfaces(),
                new LoggingInvocationHandler(logService)
        );

        //调用方法
        proxyInstance.testMethod1();
        proxyInstance.testMethod2();
        proxyInstance.testMethod3();//这个方法没有@Log注解,不会记录日志
    }
}

//定义服务接口
interface LogService {
    void testMethod1();
    void testMethod2();
    void testMethod3();
}

//实现服务接口
class LogServiceImpl implements LogService {
    @Log
    public void testMethod1() {
        try {
            Thread.sleep(100);//模拟方法执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Executing testMethod1");
    }

    @Log
    public void testMethod2() {
        try {
            Thread.sleep(150);//模拟方法执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Executing testMethod2");

    }

    @Override
    public void testMethod3() {
        try {
            Thread.sleep(50);//模拟方法执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Executing testMethod3");

    }
}